package com.ruoyi.interview.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.interview.domain.InterviewDimension;
import com.ruoyi.interview.domain.InterviewDimensionScore;
import com.ruoyi.interview.domain.InterviewReport;
import com.ruoyi.interview.domain.entity.InterviewQuestionAnswerEntity;
import com.ruoyi.interview.domain.entity.ReportResponseEntity;
import com.ruoyi.interview.mapper.InterviewDimensionMapper;
import com.ruoyi.interview.mapper.InterviewDimensionScoreMapper;
import com.ruoyi.interview.mapper.InterviewQuestionMapper;
import com.ruoyi.interview.mapper.InterviewReportMapper;
import com.ruoyi.interview.service.IInterviewReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 面试报告Service业务层处理
 * 
 * @author lishugen
 * @date 2025-11-23
 */
@Service
public class InterviewReportServiceImpl implements IInterviewReportService 
{
    @Autowired
    private InterviewReportMapper interviewReportMapper;

    @Autowired
    private InterviewDimensionMapper interviewDimensionMapper;

    @Autowired
    private InterviewQuestionMapper interviewQuestionMapper;

    @Autowired
    private InterviewDimensionScoreMapper interviewDimensionScoreMapper;

    /**
     * 查询面试报告
     * 
     * @param id 面试报告主键
     * @return 面试报告
     */
    @Override
    public InterviewReport selectInterviewReportById(Long id)
    {
        return interviewReportMapper.selectInterviewReportById(id);
    }

    /**
     * 查询面试报告列表
     * 
     * @param interviewReport 面试报告
     * @return 面试报告
     */
    @Override
    public List<InterviewReport> selectInterviewReportList(InterviewReport interviewReport)
    {
        return interviewReportMapper.selectInterviewReportList(interviewReport);
    }

    /**
     * 新增面试报告
     * 
     * @param interviewReport 面试报告
     * @return 结果
     */
    @Override
    public int insertInterviewReport(InterviewReport interviewReport)
    {
        interviewReport.setCreateTime(DateUtils.getNowDate());
        return interviewReportMapper.insertInterviewReport(interviewReport);
    }

    /**
     * 修改面试报告
     * 
     * @param interviewReport 面试报告
     * @return 结果
     */
    @Override
    public int updateInterviewReport(InterviewReport interviewReport)
    {
        interviewReport.setUpdateTime(DateUtils.getNowDate());
        return interviewReportMapper.updateInterviewReport(interviewReport);
    }

    /**
     * 批量删除面试报告
     * 
     * @param ids 需要删除的面试报告主键
     * @return 结果
     */
    @Override
    public int deleteInterviewReportByIds(Long[] ids)
    {
        return interviewReportMapper.deleteInterviewReportByIds(ids);
    }

    /**
     * 删除面试报告信息
     * 
     * @param id 面试报告主键
     * @return 结果
     */
    @Override
    public int deleteInterviewReportById(Long id)
    {
        return interviewReportMapper.deleteInterviewReportById(id);
    }

    /**
     * 生成面试记录对应面试评价的提示词
     * @param recordId
     * @return
     */
    @Override
    public String genPrompt(Long recordId) {
        //1.查询面试记录对应的岗位和维度
       List<InterviewDimension>  interviewDimensions=interviewDimensionMapper.selectByRecordId(recordId);
        //2.查询面试记录中生成问题和问题的答案
        List<InterviewQuestionAnswerEntity> questionAnswers=interviewQuestionMapper.selectQuestionAnswerByRecordId(recordId);

        //3.组织提示词字符串 调用ai获得评价

        return genPromptString(interviewDimensions,questionAnswers);
    }

    @Override
    @Transactional
    public void saveReport(ReportResponseEntity reportResponseEntity) {
        // 面试报告表
        InterviewReport interviewReport = new InterviewReport();
        interviewReport.setCreateTime(DateUtils.getNowDate());
        interviewReport.setRecordId(reportResponseEntity.getRecordId());
        interviewReport.setOverallScore(reportResponseEntity.getOverall_score());
        interviewReport.setWeaknesses(reportResponseEntity.getWeaknesses());
        interviewReport.setSuggestions(reportResponseEntity.getSuggestions());
        interviewReport.setStrengths(reportResponseEntity.getStrengths());
        interviewReport.setGenerateTime(DateUtils.getNowDate());
        interviewReport.setOverallEvaluation(reportResponseEntity.getOverall_evaluation());
        interviewReportMapper.insertInterviewReport(interviewReport);
        // 维度得分表
        reportResponseEntity.getDimension_scores().forEach(interviewDimension -> {
            InterviewDimensionScore interviewDimensionScore = new InterviewDimensionScore();
            interviewDimensionScore.setReportId(interviewReport.getId());
            interviewDimensionScore.setScore(interviewDimension.getScore());
            interviewDimensionScore.setDimensionId(interviewDimension.getDimension_id());
            interviewDimensionScore.setEvaluation(interviewDimension.getEvaluation());
            interviewDimensionScore.setCreateTime(DateUtils.getNowDate());
            interviewDimensionScoreMapper.insertInterviewDimensionScore(interviewDimensionScore);
        });


    }

    /**
     * 生成提示词
     * @param interviewDimensions
     * @param questionAnswers
     * @return
     */
    private String genPromptString(List<InterviewDimension> interviewDimensions,List<InterviewQuestionAnswerEntity> questionAnswers) {
        StringBuilder prompt = new StringBuilder("");
        prompt.append("你是一位专业的IT技术面试评估专家，需要根据候选人的面试问题和回答内容，从不同维度进行评估并生成详细的面试报告。请按照以下要求进行分析：\n");
        //评估维度
        prompt.append("### 评估维度\n");
        interviewDimensions.forEach(interviewDimension -> {
            prompt.append(String.format("%d.%s(权重%.0f%%)：评估Java专业知识、框架使用、系统设计等能力\n",
                    interviewDimension.getId(),
                    interviewDimension.getName(),
                    interviewDimension.getWeight().multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP)));
        });

        //面试问题与回答
        prompt.append("### 面试问题与回答\n");
        for (int i = 0; i < questionAnswers.size(); i++) {
            InterviewQuestionAnswerEntity questionAnswer = questionAnswers.get(i);
            prompt.append(String.format("问题%d：%s\n",i+1,questionAnswer.getQuestionContent()));
            prompt.append(String.format("回答%d：%s\n",i+1,questionAnswer.getAnswerContent()));
        }
        prompt.append("""
            ### 评估要求
            1. 对每个维度进行评分(0-100分)，并给出具体评价
            2. 生成综合评分和总体评价
            3. 分析候选人的优势和不足
            4. 提供针对性的改进建议
            5. 保持评价专业、客观且有建设性
            6. 结果为JSON格式的字符串，不需要以markdown的方式生成，直接生成内容即可

            ### 输出格式
            请严格按照以下JSON格式输出评估结果：

            {
              "overall_score": 综合评分,
              "overall_evaluation": "总体评价",
              "dimension_scores": [
                {
                  "dimension_id": 维度ID,
                  "dimension_name": 维度名称,
                  "score": 维度得分,
                  "evaluation": "维度评价"
                },
                ...
              ],
              "strengths": "优势分析",
              "weaknesses": "不足分析",
              "suggestions": "改进建议"
            }
        """);
        return prompt.toString();
    }

}
